# import_movies_script.py
import os
import django
import csv
import time
import requests
from tqdm import tqdm

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'douban_movies.settings')
django.setup()

from movies.models import Movie

with open("movies.csv", mode='r', encoding='utf-8-sig') as csvfile:
    reader = csv.DictReader(csvfile)
    total = 0
    created = 0

    created = 0
    skipped = 0
    failed = 0

    with tqdm(total=120, desc="导入电影数据", unit="部") as pbar:
        for row in reader:
            try:
                total += 1
                response = requests.get(url=row['poster'])
                f = open("media/posters/{}.jpg".format(row['title']), "wb")
                f.write(response.content)
                f.close()
                _, created_flag = Movie.objects.get_or_create(
                    title=row['title'],
                    defaults={
                        'rating': float(row['rating']),
                        'director': row['director'],
                        'actors': row['actors'],
                        'year': int(row['year']),
                        'country': row['country'],
                        'genre': row['genre'],
                        'quote': row['quote'],
                        'poster': "/media/posters/{}.jpg".format(row['title']),
                        #'poster_url': row['douban_url'],
                    }
                )
                if created_flag:
                    created += 1
                    pbar.set_postfix_str(f"新增: {created}, 跳过: {skipped}, 失败: {failed}")
                else:
                    skipped += 1
            except Exception as e:
                failed += 1
                tqdm.write(f"处理 {row['title']} 时出错: {str(e)}")
            time.sleep(0.2)
            pbar.update(1)
        
    print(f'Successfully imported {created} new movies (total processed: {total})')
